"""
serializers
Administrator
2023/12/6
convergence-server
"""
import re
from rest_framework import serializers
from .models import User, UserGroup, UserAccountBind, Employee, Message as UserMessage
from company.models import Company, Department

from utils.response_util import APIResponse

from rest_framework_simplejwt.serializers import TokenObtainPairSerializer


# 用户注册
class UserRegisterSerializer(serializers.Serializer):
    """用户注册序列化器"""
    username = serializers.CharField(max_length=150, min_length=6, label='账号(手机号)',
                                     error_messages={'required': '手机号为必填项'})
    password = serializers.CharField(max_length=128, min_length=6, write_only=True, label='密码',
                                     error_messages={'required': '密码为必填项'})
    re_password = serializers.CharField(max_length=128, min_length=6, write_only=True, label='确认密码',
                                        error_messages={'required': '验证密码为必填项'})

    @staticmethod
    def validate_username(data):
        regular_str = r"^(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57]|19[0-9]|16[0-9])[0-9]{8}$"
        if not re.match(regular_str, data):
            raise serializers.ValidationError("请输入正确的手机号")

        if User.objects.filter(username=data):
            raise serializers.ValidationError("该手机号已注册")

        return data

    def validate_password(self, data):
        regular_str = r"^\S*(?=\S{6,})(?=\S*\d)(?=\S*[A-Z])(?=\S*[a-z])(?=\S*[;.!@#$%^&*?])\S*$"
        if not re.match(regular_str, data):
            raise serializers.ValidationError(
                "密码长度为6-16位字符，且必须同时包含：大写字母、小写字母、数字和特殊字符;.!@#$%^&*?")

    def validate_re_password(self, data):
        if data != self.initial_data['password']:
            raise serializers.ValidationError("两次密码输入不一致")
        return data

    def create(self, validated_data):
        return User.objects.create_user(username=validated_data.get('username'),
                                        mobile=validated_data.get('username'),
                                        password=validated_data.get('password'))


class UserGroupSerializer(serializers.ModelSerializer):
    """用户组"""

    class Meta:
        model = UserGroup
        fields = ('id', 'rules', 'name')

    def create(self, validated_data):
        exist = UserGroup.objects.filter(name=validated_data['name']).exists()
        if exist:
            raise serializers.ValidationError('用户组已存在')

        instance = UserGroup.objects.create(**validated_data)
        return instance

    def update(self, instance, validated_data):
        exist = UserGroup.objects.filter(name=validated_data['name']).values()
        if len(exist) > 1:
            raise serializers.ValidationError('用户组已存在')

        if type(validated_data['rules']) == list:
            validated_data['rules'] = ','.join(validated_data['rules'])
        elif type(validated_data['rules']) == str:
            validated_data['rules'] = validated_data['rules']
        else:
            raise serializers.ValidationError('权限格式错误')

        UserGroup.objects.filter(pk=instance.pk).update(**validated_data)
        return instance


class UserSerializer(serializers.ModelSerializer):
    """用户"""

    class Meta:
        model = User
        exclude = ('password',)

class UpdateWebPasswordSerializer(serializers.ModelSerializer):
    """用户"""
    password = serializers.CharField(max_length=128, min_length=6, write_only=True, label='密码',
                                     error_messages={'required': '密码为必填项'})
    re_password = serializers.CharField(max_length=128, min_length=6, write_only=True, label='确认密码',
                                        error_messages={'required': '验证密码为必填项'})

    class Meta:
        model = User
        fields = ('id','password','re_password')

    def validate_password(self, data):
        regular_str = r"^\S*(?=\S{6,})(?=\S*\d)(?=\S*[A-Z])(?=\S*[a-z])(?=\S*[;.!@#$%^&*?])\S*$"
        if not re.match(regular_str, data):
            raise serializers.ValidationError(
                "密码长度为6-16位字符，且必须同时包含：大写字母、小写字母、数字和特殊字符;.!@#$%^&*?")

    def validate_re_password(self, data):
        if data != self.initial_data['password']:
            raise serializers.ValidationError("两次密码输入不一致")
        return data



class MyTokenObtainPairSerializer(TokenObtainPairSerializer):
    """重写登陆令牌"""

    def validate(self, attrs):
        data = super().validate(attrs)

        # 验证用户状态
        if self.user.is_auth == '-1':
            raise serializers.ValidationError('用户状态异常,请联系管理员操作！')
        # 验证用户状态
        if self.user.is_auth == '2':
            raise serializers.ValidationError('管理员正在进行审核中！')
        refresh = self.get_token(self.user)

        data['refresh'] = str(refresh)
        data['access'] = str(refresh.access_token)

        results = {
            'token': data['access'],
            'refresh': data['refresh'],
        }
        return APIResponse(results=results).data


class UserAccountBindSerializer(serializers.ModelSerializer):
    """用户绑定平台"""

    class Meta:
        model = UserAccountBind
        fields = (
            'id', 'user_id', 'username', 'platefrom_id', 'en_name', 'plate_account', 'add_time', "company_id", 'type',
            'company_name', 'app_account_upload')

    def create(self, validated_data):
        # 个人用户
        if validated_data['type'] == '0':
            exist = UserAccountBind.objects.filter(user_id=validated_data['user_id'],
                                                   platefrom_id=validated_data['platefrom_id'],
                                                   plate_account=validated_data['plate_account']).exists()
        elif validated_data['type'] == '1':
            exist = UserAccountBind.objects.filter(company_id=validated_data['company_id'],
                                                   platefrom_id=validated_data['platefrom_id'],
                                                   plate_account=validated_data['plate_account']).exists()

        if exist:
            raise serializers.ValidationError('已绑定')

        # 绑定操作
        instance = UserAccountBind.objects.create(**validated_data)
        return instance

    def update(self, instance, validated_data):
        # 个人用户
        if validated_data['type'] == '0':
            exist = UserAccountBind.objects.filter(user_id=validated_data['user_id'],
                                                   platefrom_id=validated_data['platefrom_id'],
                                                   plate_account=validated_data['plate_account']).exists()
        elif validated_data['type'] == '1':
            exist = UserAccountBind.objects.filter(company_id=validated_data['company_id'],
                                                   platefrom_id=validated_data['platefrom_id'],
                                                   plate_account=validated_data['plate_account']).exists()

        if exist:
            raise serializers.ValidationError('该平台已绑定')
        UserAccountBind.objects.filter(pk=instance.pk).update(**validated_data)
        return instance


class UserEmployeeSerializer(serializers.ModelSerializer):
    """用户绑定平台"""
    company_name = serializers.SerializerMethodField()
    department_name = serializers.SerializerMethodField()

    class Meta:
        model = User
        fields = (
        'id', 'username', 'mobile', 'mobile', 'company_name', 'department_name', 'company_id', 'department_id')

    def get_company_name(self, obj):
        company = Company.objects.filter(id=obj.company_id).first()
        if company:
            return company.name
        return ''

    def get_department_name(self, obj):
        department = Department.objects.filter(id=obj.department_id).first()
        if department:
            return department.name
        return ''

    def update(self, instance, validated_data):
        # 个人用户
        if validated_data['type'] == '0':
            exist = UserAccountBind.objects.filter(user_id=validated_data['department_id'],
                                                   platefrom_id=validated_data['platefrom_id'],
                                                   plate_account=validated_data['plate_account']).exists()
        elif validated_data['type'] == '1':
            exist = UserAccountBind.objects.filter(company_id=validated_data['company_id'],
                                                   platefrom_id=validated_data['platefrom_id'],
                                                   plate_account=validated_data['plate_account']).exists()

        if exist:
            raise serializers.ValidationError('该平台已绑定')
        UserAccountBind.objects.filter(pk=instance.pk).update(**validated_data)
        return instance


class MessageSerializer(serializers.ModelSerializer):
    """消息管理"""
    company_name = serializers.SerializerMethodField()

    class Meta:
        model = UserMessage
        fields = (
        'id', 'company_id', 'department_id', 'user_id','is_read', 'title', 'content', 'add_time', 'company_name')

    def create(self, validated_data):
        post_data = self.context['request'].data
        validated_data['creator_user'] = self.context['request'].user.id  # 设置 creator_user 值为当前登录用户
        validated_data['company_id'] = self.context['request'].user.company_id  # 设置 creator_user 值为当前登录用户

        # type = 1: 整个公司发消息
        insert_list = []
        if post_data['type'] == 1:
            # 所有公司的用户：
            user_list = User.objects.filter(company_id=validated_data['company_id']).values()

        #  type = 2: 部分部门发消息
        elif post_data['type'] == 2:
            user_list = User.objects.filter(department_id__in=post_data['department_ids']).values()

        #  type = 3: 部分用户发消息
        elif post_data['type'] == 3:
            user_list = User.objects.filter(id__in=post_data['user_ids']).values()
        else:
            user_list = User.objects.filter(company_id=validated_data['company_id']).values()

        for user in user_list:
            insert_item = UserMessage()
            insert_item.user_id = user['id']
            insert_item.company_id = user['company_id']
            insert_item.department_id = user['department_id']
            insert_item.title = validated_data['title']
            insert_item.content = validated_data['content']
            insert_item.is_read = 0
            insert_list.append(insert_item)
        UserMessage.objects.bulk_create(insert_list)
        return validated_data

    def get_company_name(self, obj):
        if type(obj) == dict:
            company = Company.objects.filter(id=obj['company_id']).first()
        else:
            company = Company.objects.filter(id=obj.company_id).first()
        if company:
            return company.name
        return ''
